<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="card">
      <el-alert title="注意：只允许为第三级分类设置相关参数!" type="warning" :closable="false" show-icon></el-alert>
      <!-- 分类级联选择 -->
      <el-row class="row_sel" :gutter="10">
        <el-col :span="3">选择商品分类：</el-col>
        <el-col :span="8">
          <el-cascader
            v-model="selectValue"
            :options="selectList"
            @change="selectChange"
            :props="selectOptions"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- Tabs 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数区块 -->
        <el-tab-pane label="动态参数" name="many">
          <el-row>
            <el-col :span="2">
              <el-button
                type="primary"
                :disabled="isOptBtn"
                size="mini"
                @click="showParamsDialog(0,null)"
              >添加参数</el-button>
            </el-col>
          </el-row>
          <!-- 动态参数 表格 -->
          <el-table :data="dynamicParamList" style="width: 100%" stripe border>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                {{scope.row.lenght}}
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="removeVals(index,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput((scope.row))"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                {{scope.row.lenght}}
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showParamsDialog(1,scope.row)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性区块 -->
        <el-tab-pane label="静态属性" name="only">
          <el-row>
            <el-col :span="2">
              <el-button
                type="primary"
                :disabled="isOptBtn"
                size="mini"
                @click="showParamsDialog(2,null)"
              >添加属性</el-button>
            </el-col>
          </el-row>
          <!-- 静态属性 表格 -->
          <el-table :data="staticArrList" style="width: 100%" stripe border>
            <!-- 展开列 --> 
            <el-table-column type="expand">
                <template slot-scope="scope">
                {{scope.row.lenght}}
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="removeVals(index,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput((scope.row))"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                {{scope.row.lenght}}
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showParamsDialog(3,scope.row)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog
      :title="dialogBehavior+dialogTile"
      :visible.sync="paramsDialogVisible"
      width="50%"
      @close="paramsDialogClosed"
    >
      <el-form ref="paramsFormRef" :rules="paramsFormRules" :model="paramsForm" label-width="100px">
        <el-form-item prop="attr_name" :label="dialogTile+'：'">
          <el-input v-model="paramsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="paramsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsRes">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectValue: [],
      selectList: [],
      selectOptions: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      activeName: "many",
      cateId: -1,
      dynamicParamList: [],
      staticArrList: [],
      behavior: 0, //0:添加动态参数 1:编辑动态参数 2:添加静态属性 3.编辑静态属性
      dialogBehavior: "添加",
      dialogTile: "动态参数",
      paramsDialogVisible: false,
      paramsForm: {
        attr_name: ""
      },
      paramsFormRules: {
        attr_name: [
          { required: true, message: "内容不能为空！", trigger: "blur" },
          { min: 2, max: 8, message: "长度在2到8个字符", trigger: "blur" }
        ]
      },
      editParamsId: 0
    };
  },
  created() {
    this.getCateDataList();
  },
  methods: {
    //  商品分类的请求
    getCateDataList() {
      this.$httpReq
        .get("categories", { params: { type: 3 } })
        .then(res => {
          console.log("==商品分类==>" + JSON.stringify(res));
          if (res.meta.status === 200) {
            this.selectList = res.data;
          } else {
            var msg = res.meta.msg;
            this.$message.error(msg);
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
    },
    //获取分类参数
    getAttrDataList() {
      this.$httpReq
        .get(`categories/${this.cateId}/attributes`, {
          params: { sel: this.activeName }
        })
        .then(res => {
          console.log("==参数列表==>" + JSON.stringify(res));
          if (res.meta.status === 200) {
            res.data.forEach(item => {
              console.log("==参数列表==attr_vals==>" + item.attr_vals);
              item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
              item.inputVisible = false;
              item.inputValue = "";
            });

            if (this.activeName === "many") {
              this.dynamicParamList = res.data;
              console.log(
                "==参数列表==tag==>" + JSON.stringify(this.dynamicParamList)
              );
            } else {
              this.staticArrList = res.data;
            }
          } else {
            var msg = res.meta.status;
            this.$message.error(msg);
          }
        })
        .catch(err => {
          this.$message.error(err.data);
        });
    },
    // http://push2.eastmoney.com/api/qt/kamt/get?fields1=f1,f2,f3,f4&fields2=f51,f52,f53,f54&ut=b2884a393a59ad64002292a3e90d46a5&cb=jQuery1124023677627678763313_1585728081346&_=1585728081462
    // http://56.push2.eastmoney.com/api/qt/ulist.np/get?fid=f3&pi=0&pz=40&po=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&fields=f14,f12,f13,f2,f3,f4,f6,f104,f105,f106&np=1&cb=jQuery1124023677627678763313_1585728081346&secids=100.TOP40%2C100.AS51%2C100.ATX%2C100.BFX%2C100.BVSP%2C100.TSX%2C100.PX%2C100.FCHI%2C100.HEX%2C100.GDAXI%2C100.AEX%2C100.ASE%2C100.SENSEX%2C100.ICEXI%2C100.JKSE%2C100.N225%2C100.KS11%2C100.ISEQ%2C100.MIB%2C100.KLSE%2C100.MXX%2C100.NZ50%2C100.KSE100%2C100.WIG%2C100.RTS%2C100.OMXSPI%2C100.STI%2C100.CSEALL%2C100.IBEX%2C100.SSMI%2C100.SET%2C100.TWII%2C100.FTSE%2C100.DJIA%2C100.NDX%2C100.SPX%2C100.VNINDEX&_=1585728081500
    //获取股票数据
    // getGuPiaoList() {
    //   this.$httpReq
    //     .get( "http://56.push2.eastmoney.com/api/qt/ulist.np/get?fid=f3&pi=0&pz=40&po=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&fields=f14,f12,f13,f2,f3,f4,f6,f104,f105,f106&np=1&cb=jQuery1124023677627678763313_1585728081346&secids=100.TOP40%2C100.AS51%2C100.ATX%2C100.BFX%2C100.BVSP%2C100.TSX%2C100.PX%2C100.FCHI%2C100.HEX%2C100.GDAXI%2C100.AEX%2C100.ASE%2C100.SENSEX%2C100.ICEXI%2C100.JKSE%2C100.N225%2C100.KS11%2C100.ISEQ%2C100.MIB%2C100.KLSE%2C100.MXX%2C100.NZ50%2C100.KSE100%2C100.WIG%2C100.RTS%2C100.OMXSPI%2C100.STI%2C100.CSEALL%2C100.IBEX%2C100.SSMI%2C100.SET%2C100.TWII%2C100.FTSE%2C100.DJIA%2C100.NDX%2C100.SPX%2C100.VNINDEX&_=1585728081500")
    //     .then(res => {console.log("==获取股票数据==>" + JSON.stringify(res));})
    //     .catch(err => {this.$message.error(err.data);});
    // },

    //添加动态参数或者静态属性
    addParamsRes() {
      // this.$refs.paramsFormRef.validate(valid => {});

      this.$refs.paramsFormRef.validate(valid => {
        if (!valid) {
          return;
        }
        if (this.behavior === 0 || this.behavior === 2) {
          //添加动态参数/静态属性
          this.$httpReq
            .post(`categories/${this.cateId}/attributes`, {
              attr_name: this.paramsForm.attr_name,
              attr_sel: this.activeName
            })
            .then(res => {
              console.log("==添加参数==>" + JSON.stringify(res));
              var msg = res.meta.msg;
              if (res.meta.status === 201) {
                this.$message.success(msg);
                this.paramsDialogVisible = false;
                this.getAttrDataList();
              } else {
                this.$message.error(msg);
              }
            })
            .catch(err => {
              this.$message.error(err);
            });
        } else {
          //编辑动态参数/静态属性
          this.$httpReq
            .put(`categories/${this.cateId}/attributes/${this.editParamsId}`, {
              attr_name: this.paramsForm.attr_name,
              attr_sel: this.activeName
            })
            .then(res => {
              console.log("==编辑参数==>" + JSON.stringify(res));
              var msg = res.meta.msg;
              if (res.meta.status === 200) {
                this.$message.success(msg);
                this.paramsDialogVisible = false;
                this.getAttrDataList();
              } else {
                this.$message.error(msg);
              }
            })
            .catch(err => {
              this.$message.error(err);
            });
        }
      });
    },
    //删除动态参数或者静态属性
    deleteParamsRes(id) {
      this.$httpReq
        .delete(`categories/${this.cateId}/attributes/${id}`)
        .then(res => {
          var msg = res.meta.msg;
          if (res.meta.status == 200) {
            this.$message.success("删除" + this.dialogTile + "成功");
            this.getAttrDataList();
          } else {
            this.$message.error(msg);
          }
        })
        .catch(err => this.$message(err));
    },

    //选择框 选中改变监听
    selectChange() {
      if (this.selectValue.length < 3) {
        this.selectValue = []; 
        this.dynamicParamList = [];
        this.staticArrList = [];
        return;
      }
      this.cateId = this.selectValue[2];
      console.log("===选择分类===>" + this.selectValue);
      this.getAttrDataList();
    },
    //tabs标签页改变监听
    handleClick() {
      console.log("当前标签页===>", this.activeName);
      if (this.selectValue.length >= 3) {
        this.getAttrDataList();
      } 
      if (this.activeName === "many") {
        this.dialogTile = "动态参数";
      } else {
        this.dialogTile = "静态属性";
      }
    },
    //添加编辑动态参数和静态属性 的dialog弹窗关闭监听
    paramsDialogClosed() {
      console.log("======paramsDialogClosed===>");
      this.$refs.paramsFormRef.resetFields();
      this.paramsForm.attr_name = "";
      this.editParamsId = 0;
    },
    // 显示弹窗
    showParamsDialog(stateNum, data) {
      console.log(
        "===显示弹窗==stateNum===>" + stateNum + "====data===>" + data
      );
      this.behavior = stateNum;
      if (stateNum === 0) {
        this.dialogBehavior = "添加";
      } else if (stateNum === 1) {
        this.dialogBehavior = "编辑";
        this.paramsForm.attr_name = data.attr_name;
        this.editParamsId = data.attr_id;
      } else if (stateNum === 2) {
        this.dialogBehavior = "添加";
      } else if (stateNum === 3) {
        this.dialogBehavior = "编辑";
        this.editParamsId = data.attr_id;
        this.paramsForm.attr_name = data.attr_name;
      }

      this.paramsDialogVisible = true;
    },
    deleteParams(id) {
      this.$confirm(
        "此操作将永久删除该" + this.dialogTile + ", 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          this.deleteParamsRes(id);
        })
        .catch(err => {
          console.log(err);
          this.$message("取消删除权限");
        });
    },
    //显示tag输入框
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick(() => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    //tag输入框关闭监听回调
    handleInputConfirm(row) {
      row.inputValue = row.inputValue.trim();
      console.log("=====tag输入框关闭监听回调=======>" + row.inputValue.length);
      row.inputVisible = false;
      if (row.inputValue.length === 0) {
        return;
      }
      row.attr_vals.push(row.inputValue);
      row.inputValue = "";
      this.addAttrValsRes(row);
    },

    //删除参数的tag
    removeVals(index,row) { 
    this.$confirm(
        "此操作将永久删除“" + row.attr_vals[index] + "”, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => { 
      row.attr_vals.splice(index);
       console.log("======删除参数的tag======>" + row.attr_vals);
       this.addAttrValsRes(row);
        })
        .catch(err => {
          console.log(err);
          this.$message("取消删除权限");
        });
    },

//添加参数的tag
    addAttrValsRes(row) {
        this.$httpReq
            .put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
              attr_name: row.attr_name,
              attr_sel: this.activeName,
              attr_vals:row.attr_vals.join(" "),
            })
            .then(res => {
              console.log("==更新tag==>" + JSON.stringify(res));
              var msg = res.meta.msg;
              if (res.meta.status === 200) {
                this.$message.success(msg); 
                this.getAttrDataList();
              } else {
                this.$message.error(msg);
              }
            })
            .catch(err => {
              this.$message.error(err);
            });
    }

  },
  computed: {
    isOptBtn() {
      const len = this.selectValue.length;
      if (len < 3) {
        return true;
      } else {
        return false;
      }
    }
  }
};
</script>

<style   scoped>
.row_sel {
  margin-top: 15px;
  margin-bottom: 15px;
  /* background-color: greenyellow;  */
  display: flex;
  align-items: center;
  font-size: 15px;
}
.input-new-tag {
  width: 120px;
}
/* .el-tab-pane {
  display: flex;
} */
</style> 